<?php
/**
 * It will run to fetch daily deals in Finland.
 * 
 * Yawii 版权所有 © 2012
 */
class FetchCommand extends CConsoleCommand {
	
	public function run($args) {
		echo "Running Fetch: \n";
		print_r($args);
		
		$debug = $args[0];
		$command = $args[1];
		
		date_default_timezone_set('Europe/Helsinki');
		
		//load libs from extensions folder
		require_once(Yii::app()->basePath . '/vendors/simple_html_dom.php');
		
		switch ($command) {
			case 'osuma':
				require_once(Yii::app()->basePath . '/vendors/osuma/OsumaFetcher.php');
				$osuma = new OsumaFetcher();
				$osuma->search();
				break;
			case 'osuma_db':
				//update osuma merchants in database
				require_once(Yii::app()->basePath . '/vendors/osuma/OsumaFetcher.php');
				$osuma = new OsumaFetcher();
				$osuma->save();
				break;
			case 'osuma_detail':
				//update osuma merchants in database
				require_once(Yii::app()->basePath . '/vendors/osuma/OsumaFetcher.php');
				$osuma = new OsumaFetcher();
				$osuma->update();
				break;
			case 'foursquare':
				//fetch the foursquare.com
				$this->getPlaceFoursquare();
				break;
			case 'incentz':
				//fetch the incentz.com
				$this->getCouponIncentz();
				break;
			case 'bellycard':
				//fetch the bellycard.com
				$this->getRewardBelly();
				break;
			case 'getperka':
				//fetch the getperka.com
				$this->getRewardPerka();
				break;
			case 'perkablog':
				//fetch the getperka.com
				$this->getRewardPerkaBlog();
				break;
			default:
				echo "command format: \n"
					."php -q I:\xampp\htdocs\yamii.fi\index-cron.php fetch debug [command]\n"
					."[command]\n"
					."- incentz\n"
					."- bellycard\n"
					."- getperka\n"
					."- perkablog\n";
				break;
		}
		
		echo "end of command.\n";
	}
	
	/**/
	public function getPlaceFoursquare() {
		echo str_replace(array(' ', '-'), '', '09 9876-3455 545-456');
	}
	
	public function getCouponIncentz() {
		$site_address = 'http://incentz.com/web/offers.html';
		
		$offset = 0;
		$max_offet = 90;
		$next = true;
		
		$coupon_list = array();
		while ($next) {
			$next = false;

			$web_url = $site_address . '?offset=' . $offset;
			
			echo $web_url . "\n";
			
			//get all coupon list link
			$html = file_get_html($web_url);
			foreach ($html->find('#coupon-list > li') as $coupon) {
				$r = array(
					'id' => $coupon->id
				);
				$wrapper = $coupon->find('.coupon-content', 0);
				if (!empty($wrapper)) {
					$title = $wrapper->find('.title', 0);
					$r['coupon_title'] = trim($title->plaintext);
					$r['coupon_url'] = $title->href;
					
					$brand = $wrapper->find('.brand-name', 0);
					$r['brand_name'] = trim($brand->plaintext);
					$r['brand_url'] = $brand->href;
				}
				$wrapper = null;
				$wrapper = $coupon->find('.coupon-actions', 0);
				if (!empty($wrapper)) {
					$category = $wrapper->find('.main-category', 0);
					$r['brand_category'] = trim($category->plaintext);
					
					$expiry_date = $wrapper->find('.expiry-date > strong', 0);
					$r['coupon_end'] = trim($expiry_date->plaintext);
				}
				$wrapper = null;
				$wrapper = $coupon->find('.geo', 0);
				if (!empty($wrapper)) {
					$lat = $wrapper->find('.latitude', 0);
					$r['brand_lat'] = trim($lat->plaintext);
					$lng = $wrapper->find('.longitude', 0);
					$r['brand_lng'] = trim($lng->plaintext);
				}
				$coupon_list[] = $r;

				$next = true;
			}
			$html->clear();
			unset($html);

			$offset+=10;
		}

		file_put_contents(Yii::app()->basePath . '/runtime/icz'.date('Ymd').'.txt', json_encode($coupon_list));
		file_put_contents(Yii::app()->basePath . '/runtime/icz'.date('Ymd').'.log', print_r($coupon_list, 1));
	}
	
	public function getRewardBelly() {
		$site_address = 'https://bellycard.com/businesses/';
		
		//business id: 12990 - 21630
		$min_offset = 20021;
		$max_offset = 21630;
		
		file_put_contents(Yii::app()->basePath . '/runtime/belly-'.date('Ymd').'.csv', '');
		$business_list = array();
		for ($i = $min_offset; $i <= $max_offset; $i ++) {
			$web_url = $site_address . $i;
			echo $web_url . "\n";
			
			$html = null;
			$row = null;
			try {
				//fetch business page
				$html = file_get_html($web_url);
				$doc_biz = $html->find('.content', 0);
				if (empty($doc_biz)) {
					$html->clear();
					unset($html);
					continue;
				}
				$name = trim($doc_biz->find('h1', 0)->plaintext);
				if (empty($name)) {
					$html->clear();
					unset($html);
					continue;
				}
				$category = trim($doc_biz->find('.category', 0)->plaintext);

				$row = array(
					'belly_id' => $i,
					'name' => $name,
					'category' => $category,
					'rewards' => null,
				);

				
				//get rewards list
				foreach ($html->find('li.reward') as $doc_reward) {
					$points = trim($doc_reward->find('.num', 0)->plaintext);
					$title = trim($doc_reward->find('.desc', 0)->plaintext);
					$message = trim($doc_reward->find('.message', 0)->plaintext);

					$row['rewards'][] = array(
						'points' => $points,
						'title' => $title,
						'message' => $message,
					);

					$line = "{$row['belly_id']};{$row['name']};{$row['category']};{$points};{$title};{$message}";
					file_put_contents(Yii::app()->basePath . '/runtime/belly-'.date('Ymd').'.csv', $line."\n", FILE_APPEND);
				}
				$html->clear();
				unset($html);
			} catch (Exception $ex) {
				if (!empty($html)) $html->clear();
				unset($html);
				echo $ex->getTraceAsString();
				
				continue;
			}
			
			if (!empty($row)) $business_list[] = $row;
		}
	}
	
	public function getRewardPerka() {
		$site_url = 'http://getperka.com/api/2/merchant/locations';
		//$string = file_get_contents($site_url);
		$string = file_get_contents(Yii::app()->basePath . '/runtime/perka-'.date('Ymd').'-b.json');
		$array = json_decode($string, true);
		
		$business_list = array();
		file_put_contents(Yii::app()->basePath . '/runtime/perka-'.date('Ymd').'.csv', '');
		$rows = $array['data']['merchant'];
		for ($i=0; $i<count($rows); $i++) {
			$merchant = $rows[$i];
			$row = array(
				'perka_id' => $merchant['uuid'],
				'name' => $merchant['name'],
				'category' => trim(str_replace(array('Free','is','Awesome','!'), '', $merchant['headline'])),
				'loyaltyType' => $merchant['loyaltyType'],
				'pointsSignupBonus' => $merchant['pointsSignupBonus'],
				'terms' => $merchant['terms'],
				'rewards' => null,
			);
			
			$web_url = 'https://getperka.com/api/2/merchant/' . $row['perka_id'];
			echo "{$i} : " . $web_url . "\n";
			
			//fetch business page
			$line = null;
			$string = file_get_contents($web_url);
			$array = json_decode($string, true);
			if (isset($array['data']['pointsCatalogItem'])) {
				foreach ($array['data']['pointsCatalogItem'] as $reward) {
					$r = array(
						'points' => $reward['pointsRequired'],
						'title' => $reward['label'],
						'message' => 'POINT',
					);

					$line = "{$row['perka_id']};{$row['name']};{$row['category']};{$r['points']};{$r['title']};{$r['message']}\n";
					file_put_contents(Yii::app()->basePath . '/runtime/perka-'.date('Ymd').'.csv', $line, FILE_APPEND);

					$row['rewards'][] = $r;
				}
			}
			if (isset($array['data']['program'])) {
				foreach ($array['data']['program'] as $reward) {
					$r = array(
						'points' => $reward['punchesNeeded'],
						'title' => trim($reward['freeItem'] . ' ' . $reward['punchesNeededPrefix'] . ' ' . $reward['punchesNeeded'] . ' ' . $reward['punchesNeededSuffix']),
						'message' => 'PUNCHCARD',
					);

					$line = "{$row['perka_id']};{$row['name']};{$row['category']};{$r['points']};{$r['title']};{$r['message']}\n";
					file_put_contents(Yii::app()->basePath . '/runtime/perka-'.date('Ymd').'.csv', $line, FILE_APPEND);
					$row['rewards'][] = $r;
				}
			}
			//add a signup bounus
			if ($merchant['pointsSignupBonus'] > 0) {
				$r = array(
					'points' => $merchant['pointsSignupBonus'],
					'title' => $merchant['pointsSignupBonus'] . ' points on your first visit',
					'message' => 'BONUS',
				);

				$line = "{$row['perka_id']};{$row['name']};{$row['category']};{$r['points']};{$r['title']};{$r['message']}\n";
				file_put_contents(Yii::app()->basePath . '/runtime/perka-'.date('Ymd').'.csv', $line, FILE_APPEND);

				$row['rewards'][] = $r;
			}
			
			$business_list[] = $row;
		}
	}
	
	public function getRewardPerkaBlog() {
		$site_url = 'http://blog.getperka.com/perkapost';
		
		$papers = array();
		for ($i=1; $i<13; $i++) {
			$web_url = $site_url . '?page=' . $i;
			echo $web_url . "\n";
			
			$html = null;
			try {
				//fetch business page
				$html = file_get_html($web_url);
				if (empty($html)) {
					$html->clear();
					unset($html);
					continue;
				}
				
				//get title
				foreach ($html->find('.title a') as $doc_link) {
					$url = trim($doc_link->href);
					$title = trim($doc_link->plaintext);
					
					$row = array(
						'title' => $title,
						'url' => $url,
					);
					
					$papers[] = $row;
				}
				$html->clear();
				unset($html);
			} catch (Exception $ex) {
				if (!empty($html)) $html->clear();
				unset($html);
				echo $ex->getTraceAsString();
				
				continue;
			}
		}
		
		file_put_contents(Yii::app()->basePath . '/runtime/perka.blog-'.date('Ymd').'.log', print_r($papers, 1));
	}
	
	public function saveRewardBelly() {
		//save to csv file
		$string = file_get_contents(Yii::app()->basePath . '/runtime/belly-'.date('Ymd').'.txt');
		file_put_contents(Yii::app()->basePath . '/runtime/belly-'.date('Ymd').'-full.csv', '');//empty file
		$array = json_decode($string, true);
		foreach ($array as $row) {
			$line = "{$row['belly_id']};{$row['name']};{$row['category']};";
			foreach ($row['rewards'] as $r) {
				$line .= "{$r['points']};{$r['title']};{$r['message']}";
			}
			file_put_contents(Yii::app()->basePath . '/runtime/belly-'.date('Ymd').'-full.csv', $line."\n", FILE_APPEND);
		}
	}
	
	/**
	 *
	 * @param type $tag
	 * @param type $array
	 * @param type $url
	 * @return array 
	 */
	private function _rss_to_array($tag, $array, $url) {
		$doc = new DOMdocument();
		$doc->load($url);
		$rss_array = array();
		$items = array();
		foreach($doc->getElementsByTagName($tag) AS $node) {    
			foreach($array AS $key => $value) {
				$items[$value] = $node->getElementsByTagName($value)->item(0)->nodeValue;
			}
			array_push($rss_array, $items);
		}
		return $rss_array;
	}
}